package com.hsmw.schedule.task;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hsmw.schedule.mapper.HsmwDriverUserMapper;
import com.hsmw.schedule.mapper.HsmwHtnUserMapper;
import com.hsmw.schedule.mapper.HsmwUserDriverMapper;
import com.hsmw.schedule.service.HsmwBanDriverService;
import com.hsmw.schedule.service.HsmwDriverNewsService;
import com.hsmw.schedule.service.HsmwReportService;
import com.hsmw.schedule.service.HsmwVehicleService;
import com.hsmw.schedule.utils.TencentPushUtils;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


@Component
@EnableScheduling
@Configuration
@Slf4j
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class DriverLeaveScheduledTask {


    @Autowired
    private HsmwReportService hsmwReportService;

    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;

    @Autowired
    private HsmwVehicleService hsmwVehicleService;

    @Autowired
    private HsmwBanDriverService hsmwBanDriverService;



    @Autowired
    private HsmwDriverNewsService hsmwDriverNewsService;


    @Autowired
    private HsmwHtnUserMapper hsmwHtnUserMapper;



    @Autowired
    private HsmwDriverUserMapper hsmwDriverUserMapper;


    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.certificateOutDated}")
    private int certificateOutDated;

    @Value(value = "${sms.certificateOutDating}")
    private int certificateOutDating;







    //@Scheduled(cron = "0 */1 * * * ?")
    private void DriverLeave() {

        log.info("查询司机请假定时任务开始时间：" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        // 上报信息中为请假类型 且 审批类型为已通过
        List<HsmwReport> hsmwReports = hsmwReportService.list(new LambdaQueryWrapper<HsmwReport>()
                .eq(HsmwReport::getReportType, '1')
                .eq(HsmwReport::getExamineType, "1")
                );
        if (CollectionUtil.isNotEmpty(hsmwReports)) {
            hsmwReports.stream().forEach(hsmwReport -> {

                LocalDate startTime = hsmwReport.getStartTime();
                LocalDate endTime = hsmwReport.getEndTime();
                LocalDate now = LocalDate.now();

                String driId = hsmwReport.getDriId();
                HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectById(driId);
                //上报信息中 开始时间，结束时间不为null 且 当前时间在开始时间之后，在结束时间之前（在开始时间与结束时间区间内）
                if (startTime != null && endTime != null && ((now.isBefore(endTime) || now.equals(endTime)) && (now.isAfter(startTime) || now.equals(startTime))) && !StringUtils.equals("请假中",hsmwUserDriver.getWorkStatus()) && StringUtils.equals("0",hsmwReport.getAdvanceFlag())) {
                    // 则修改司机信息 状态为 请假中
                    hsmwUserDriver.setWorkStatus("请假中");
                    hsmwUserDriverMapper.updateById(hsmwUserDriver);
                }
                if (startTime != null && endTime != null && now.isAfter(endTime) && StringUtils.equals("请假中",hsmwUserDriver.getWorkStatus())) {
                    //当前时间在结束时间之后 证明请假时间已过时 修改司机状态为：休息中
                    hsmwUserDriver.setWorkStatus("休息中");
                    hsmwUserDriverMapper.updateById(hsmwUserDriver);
                }

            });
        }
        log.info("查询司机请假定时任务结束时间：------>" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

    }



    @Scheduled(cron = "0 30 0 * * ?")
    //@Scheduled(cron = "0 */1 * * * ?")
    private void vehicleStatus() {

        log.info("查询车辆信息是否过期任务开始时间：" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        LocalDate now = LocalDate.now();
        List<HsmwVehicle> hsmwVehicles = hsmwVehicleService.list();
        hsmwVehicles.stream().forEach(hsmwVehicle ->{

            //商业险保单到期时间
            LocalDate commercialInsuranceTime = hsmwVehicle.getCommercialInsuranceTime();
            // 交强险保单到期时间
            LocalDate compuTrafficTime = hsmwVehicle.getCompuTrafficTime();
            //行驶证到期时间
            LocalDate drivingLicenseTime = hsmwVehicle.getDrivingLicenseTime();
            String id = hsmwVehicle.getId();
            List<HsmwUserDriver> userDrivers = hsmwUserDriverMapper.selectList(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getVehicleId, id));

            if(now.isAfter(commercialInsuranceTime) || now.isAfter(compuTrafficTime) || now.isAfter(drivingLicenseTime)){
                // 三者满足一个其中 一个条件 修改车辆状态为：已到期
                hsmwVehicle.setWorkStatus(CommonConstants.VEHICLE_EXPIRATION);
                hsmwVehicleService.updateById(hsmwVehicle);
            }

            if(now.plusDays(30).equals(compuTrafficTime) || now.plusDays(30).equals(commercialInsuranceTime) || now.plusDays(30).equals(drivingLicenseTime)){

                if(CollectionUtil.isNotEmpty(userDrivers)){
                    for (HsmwUserDriver userDriver : userDrivers) {
                        HsmwDriverUser user = hsmwDriverUserMapper.selectById(userDriver.getUserId());
                        //回访成功之后 发送推送给司机
                        String msg = "您的保险或者行驶证还有30天到期，请尽快处理！";
                        //对APP进行离线推送
                        TencentPushUtils.pushMsg(msg,user.getUsername(),"has_new_message");
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setAlreadyRead("0");
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setUserId(userDriver.getUserId());
                        hsmwDriverNewsService.save(hsmwDriverNews);
                        String message = "保险或者行驶证";
                        SendSmsUtil.sendBizOrderSmsCode(appId, appKey, message,certificateOutDating, smsSign, user.getUsername());
                    }
                }

            }


            if(now.equals(compuTrafficTime) || now.equals(commercialInsuranceTime) || now.equals(drivingLicenseTime)){

                if(CollectionUtil.isNotEmpty(userDrivers)){
                    for (HsmwUserDriver userDriver : userDrivers) {
                        HsmwDriverUser user = hsmwDriverUserMapper.selectById(userDriver.getUserId());
                        //回访成功之后 发送推送给司机
                        String msg = "您的保险或者行驶证已经到期，无法继续接单，请知晓！";
                        //对APP进行离线推送
                        TencentPushUtils.pushMsg(msg,user.getUsername(),"has_new_message");
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setAlreadyRead("0");
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setUserId(userDriver.getUserId());
                        hsmwDriverNewsService.save(hsmwDriverNews);

                        String message = "保险或者行驶证";
                        SendSmsUtil.sendBizOrderSmsCode(appId, appKey, message,certificateOutDated, smsSign, user.getUsername());
                    }
                }

            }

            if(now.equals(compuTrafficTime) || now.equals(commercialInsuranceTime)){
                if(CollectionUtil.isNotEmpty(userDrivers)){
                    String ownCompanyId = userDrivers.get(0).getOwnCompanyId();
                    List<HsmwHtnUser> hsmwHtnUsers = hsmwHtnUserMapper.selectList(new LambdaQueryWrapper<HsmwHtnUser>().eq(HsmwHtnUser::getOwnCompanyId, ownCompanyId));
                    for (HsmwHtnUser hsmwHtnUser : hsmwHtnUsers) {
                        //回访成功之后 发送推送给司机
                        String msg = hsmwVehicle.getVehiclePlate()+"车辆的保险已经到期，无法继续接单，请知晓！";
                        //对APP进行离线推送
                        TencentPushUtils.pushMsg(msg,hsmwHtnUser.getUsername(),"has_new_message");
                        HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
                        hsmwDriverNews.setAlreadyRead("0");
                        hsmwDriverNews.setMessage(msg);
                        hsmwDriverNews.setUserId(hsmwHtnUser.getId());
                        hsmwDriverNewsService.save(hsmwDriverNews);
                    }
                }

            }


        });


        log.info("查询车辆信息是否过期任务开始时间：------>" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

    }


    //@Scheduled(cron = "0 30 0 * * ?")
    @Scheduled(cron = "0 */1 * * * ?")
    private void banDriver() {

        log.info("查询车辆封禁开始时间：" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime now = LocalDateTime.now();
        List<HsmwBanDriver> hsmwBanDrivers = hsmwBanDriverService.list(new LambdaQueryWrapper<HsmwBanDriver>().eq(HsmwBanDriver::getStatus, "1"));
        hsmwBanDrivers.stream().forEach(hsmwBanDriver ->{

            LocalDateTime durationEndTime = hsmwBanDriver.getDurationEndTime();
            String driverId = hsmwBanDriver.getDriverId();
            if(now.isAfter(durationEndTime)){

                hsmwBanDriver.setStatus("2");
                hsmwBanDriverService.updateById(hsmwBanDriver);
                if(StringUtils.isNotBlank(driverId)){
                    HsmwUserDriver userDriver = hsmwUserDriverMapper.selectById(driverId);
                    userDriver.setWorkStatus(CommonConstants.DRIVER_FREE);
                    hsmwUserDriverMapper.updateById(userDriver);
                }

            }

        });
        log.info("查询车辆封禁开始时间：------>" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

    }


    /**
     * requestVehicle 超过二十四小时删除信息
     */
    //@Scheduled(cron = "0 */1 * * * ?")
    private void reuqestVehicle() {

        log.info("车辆超过二十四小时的信息：" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));




        log.info("车辆超过二十四小时的信息：------>" + new DateTime().toString("yyyy-MM-dd HH:mm:ss"));

    }

}
